import React, { Component } from "react";
import UserList from "../components/UserList";
import Adduser from "../components/Adduser";

export default class User extends Component {
    constructor () {
        super();
        this.state = {
            list: [
                { id: 1, username: "leson", userage: 18 },
                { id: 2, username: "lili", userage: 19 },
                { id: 3, username: "lulu", userage: 20 },
            ], //用户的集合
        };
    }
    //新增的方法
    addListItem = (item) => {
        if (this.state.list.some((info) => info.username === item.username)) {
            alert("该用户名已经存在");
            return false;
        }

        let id = 1;
        if (this.state.list.length) {
            //数组有长度
            //找到数组中最大的id  +1
            //找到id的集合 进行倒序  倒序里面的第一个
            id = this.state.list.map((item) => item.id).sort((a, b) => b - a)[0] + 1;
        }
        this.setState({
            list: [...this.state.list, { ...item, id }],
        });
    };

    //删除的方法
    delListById = (id) => {
        this.setState({
            list: this.state.list.filter((item) => item.id !== id),
        });
    };

    //修改的方法
    changeListById = (id, username, userage) => {
        this.setState({
            list: this.state.list.map(item => {
                if (item.id === id) {
                    item.username = username
                    item.userage = userage
                }
                return item
            })
        })

    }
    render() {
        return (
            <div>
                <div>todoList</div>
                <Adduser addListItem={this.addListItem}></Adduser>
                <UserList list={this.state.list} delListById={this.delListById} changeListById={this.changeListById}></UserList>
            </div>
        );
    }
}